<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="loginFormRef"
        >
          <h1>Hello</h1>
          <h2>欢迎登录</h2>
          <el-form-item prop="username">
            <el-input
              placeholder="请输入用户名"
              :prefix-icon="User"
              v-model="loginForm.username"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              v-model="loginForm.password"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loading"
              class="login_btn"
              type="primary"
              @click="login"
            >
              登录
            </el-button>
          </el-form-item>
          <div style="text-align: center">
            <el-link style="color: white" :underline="false" @click="register">
              注册
            </el-link>
          </div>
        </el-form>
      </el-col>
    </el-row>
  </div>
  <!-- 注册表单 -->
  <el-dialog v-model="dialogFormVisible" title="" width="600">
    <el-form :model="registerForm" :rules="rules" ref="registerFormRef">
      <el-form-item
        label="用户名"
        :label-width="formLabelWidth"
        prop="username"
      >
        <el-input
          v-model="registerForm.username"
          autocomplete="off"
          placeholder="请输入用户名"
          style="width: 90%"
        />
      </el-form-item>
      <el-form-item label="昵称" :label-width="formLabelWidth">
        <el-input
          v-model="registerForm.nickname"
          autocomplete="off"
          placeholder="请输入昵称"
          style="width: 90%"
        />
      </el-form-item>
      <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="输入密码"
          show-password
          style="width: 90%"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="确认密码"
        :label-width="formLabelWidth"
        prop="repassword"
      >
        <el-input
          v-model="registerForm.repassword"
          type="password"
          placeholder="再次输入密码"
          show-password
          style="width: 90%"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRegister" :loading="loadingReg">
          注册
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import useUserStore from '@/store/modules/user'
import { getTime } from '@/utils/time'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage, ElNotification } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
let $router = useRouter()
let $route = useRoute()
let redirect = $route.query.redirect
let userStore = useUserStore()
let loading = ref(false) // 作登录窗口的动画
let loadingReg = ref(false)
let loginFormRef = ref()
let registerFormRef = ref()
let loginForm = reactive({
  username: 'admin',
  password: '123456',
})
// 自定义校验方法
const validatorPass = (rule: any, value: any, callback: any) => {
  // rule: 校验规则对象
  // value:校验数据的文本
  // callback: 如果符合条件，放行；不符合，则注入错误信息
  if (/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\s\S]{6,16}$/.test(value)) {
    //至少一个大写一个小写 6-16位
    callback()
  } else {
    callback(new Error('至少一个大写一个小写 6-16位'))
  }
}
const validatorRepass = (rule: any, repassword: any, callback: any) => {
  if (repassword === registerForm.value.password) {
    callback()
  } else {
    callback(new Error('两次输入密码不一致'))
  }
}
// let loginTime = getTime()
const login = async () => {
  // 可以用.then 写法
  // 加载效果
  await loginFormRef.value.validate()
  loading.value = true

  try {
    await userStore.login(loginForm)
    // 判断是否有query的redirect参数，没有就去首页
    if (redirect) {
      $router.push(redirect)
    } else {
      $router.push('/')
    }
    ElNotification({
      type: 'success',
      message: '登录成功',
      title: `Hi！${getTime()}好！`,
    })
  } catch (error: any) {
    console.log('@@@', error)
    ElNotification({
      type: 'error',
      message: error.response.data.msg,
      // message: error.response.message,
    })
  }
  loading.value = false
}
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 15, message: '长度在5至15位', trigger: 'change' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在6至15位', trigger: 'change' },
    // { validator: validatorPass, trigger: 'change' },
  ],
  repassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    // { min: 6, max: 15, message: '长度在6至15位', trigger: 'change' },
    { validator: validatorRepass, trigger: 'blur' },
  ],
}
const dialogFormVisible = ref(false)
const formLabelWidth = '80px'
const registerForm = ref({
  username: 'YYYYYY',
  password: '111111',
  repassword: '111111',
  nickname: 'UIOP',
})
const register = () => {
  dialogFormVisible.value = true
  registerFormRef.value.clearValidate() // 每次打开前去除验证
  // 清空字段
  registerForm.value.username = ''
  registerForm.value.password = ''
  registerForm.value.repassword = ''
  registerForm.value.nickname = ''
}
const submitRegister = async () => {
  // await registerFormref
  await registerFormRef.value.validate()
  loadingReg.value = true
  try {
    // 发送注册请求
    await userStore.registerUser(registerForm.value)
    dialogFormVisible.value = false
    $router.push('/')
    ElNotification({
      type: 'success',
      message: '注册成功，请登录！',
    })
  } catch (error: any) {
    ElMessage({
      type: 'error',
      message: error.message,
    })
  }
  loadingReg.value = false
}
</script>
<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;

  .login_form {
    position: relative;
    top: 30vh;
    width: 80%;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: cover;
    padding: 40px;

    h1 {
      color: white;
      font-size: 40px;
    }

    h2 {
      font-size: 20px;
      color: white;
      margin: 20px 0;
    }

    .login_btn {
      width: 100%;
    }
  }
}
</style>
